var MongoClient = require('mongodb').MongoClient;

var driver = {};

driver.connect = function (callback,url) {

    MongoClient.connect(url, function (err, db) {
        var error;
        if (err) {
            error = { success: false, error: '数据库连接失败', msg: '数据库连接失败' };
        } else {
            callback(err, db);
        }
    });
};

driver.update = function (db, callback, table, update) {
    db.collection(table).update(query, update, function (err, result) {
        var res;
        var error;
        if (err) {
            error = { success: false, error: '查询异常', msg: '查询异常' };
        } else {

            res = { success: true, data: result };
        }

        db.close();

        callback(error, res);

    });
};

driver.insert = function (db, callback, table, query) {
    db.collection(table).insertOne(query).toArray(function (err, result) {
        var res;
        var error;
        if (err) {
            error = { success: false, error: '查询异常', msg: '查询异常' };
        } else {

            res = { success: true, data: result };
        }

        db.close();

        callback(error, res);


    });
};

driver.find = function (db, callback, table, query) {
    db.collection(table).find(query).toArray(function (err, result) {
        var res;
        var error;
        if (err) {
            error = { success: false, error: '查询异常', msg: '查询异常' };
        } else {

            res = { success: true, data: result };
        }

        db.close();

        callback(error, res);


    });
};

module.exports = driver;